package edu.polsl.bio.str.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.management.ManagementFactory;
import java.net.*;
import java.util.Enumeration;

/**
 * //todo class description
 * <p/>
 * Created on: Jun 12, 2011 6:12:04 PM <br/>
 * <a href="http://www.polsl.pl">www.polsl.pl</a>
 *
 * @author lukasz.olczak@polsl.pl
 */
public class SystemUtils {
  /**
   * slf4j Logger.
   */
  private static final Logger log = LoggerFactory.getLogger(SystemUtils.class.getName());


  public static String getNonLoopbackAddress() throws UnknownHostException {
    try {
      Enumeration<NetworkInterface> enumer = NetworkInterface.getNetworkInterfaces();
      while (enumer.hasMoreElements()) {
        NetworkInterface ni = enumer.nextElement();
        if (ni.isVirtual() || ni.isLoopback() || ni.getDisplayName().toLowerCase().contains("vmnet")) {
          continue;
        }

        for (InterfaceAddress ia : ni.getInterfaceAddresses()) {
          if (ia.getAddress() instanceof Inet4Address) {
            return ia.getAddress().getHostAddress();
          }
        }
      }

    } catch (SocketException e) {
      throw new RuntimeException(e);
    }
    throw new UnknownHostException("Can't find host address");
  }

  public static double getSystemLoad() {
    return ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage();
  }
}
